package argo.hot100.tree;

import java.util.HashMap;
import java.util.Map;

public class BuildTree {


    Map<Integer, Integer> inorderInxMp = new HashMap<>();


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null) {
            return null;
        }
        for (int i = 0; i < inorder.length; i++) {
            inorderInxMp.put(inorder[i], i);
        }

        return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode build(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
        if (preLeft > preRight) {
            return null;
        }
        int rootVal = preorder[preLeft];
        TreeNode root = new TreeNode(rootVal);
        Integer inOrderRootInx = inorderInxMp.get(rootVal);
        int leftSize = inOrderRootInx - inLeft;

        root.left = build(preorder, inorder, preLeft + 1, preLeft + leftSize, inLeft, inOrderRootInx - 1);
        root.right = build(preorder, inorder, preLeft + leftSize + 1, preRight, inOrderRootInx + 1, inRight);
        return root;

    }


}
